<?php

	namespace org\tekuna\demo\weblog\action;
	
	use org\tekuna\framework\response\http\UrlRedirectResponse;

	use org\tekuna\demo\weblog\manager\ArticleManager;

	use org\tekuna\demo\weblog\manager\CommentManager;

	use org\tekuna\demo\weblog\model\Comment;

	use org\tekuna\framework\filter\data\NoHtmlFilter;

	use org\tekuna\framework\filter\data\IntegerFilter;

	use org\tekuna\framework\request\Request;
	use org\tekuna\framework\action\ActionEvent;
	use org\tekuna\framework\action\AbstractAction;

	
	class AddCommentAction extends AbstractAction {
		
		private
			$objCommentManager,
			$objArticleManager;
			
		
		public function execute(ActionEvent $objActionEvent, Request $objRequest) {
			
			// set filters
			$objRequest -> setPostFilter('article-id', new IntegerFilter());
			$objRequest -> setPostFilter('author', new NoHtmlFilter());
			$objRequest -> setPostFilter('text', new NoHtmlFilter());
			
			// get values
			$iArticleId = $objRequest -> getPostValue('article-id');
			$sAuthor = $objRequest -> getPostValue('author');
			$sText = $objRequest -> getPostValue('text');
			
			// build entity
			$objComment = new Comment();
			$objComment -> articleId = $iArticleId;
			$objComment -> author = $sAuthor;
			$objComment -> text = $sText;
			$objComment -> creationDate = time();
			
			// save entity
			$this -> objCommentManager -> save($objComment);
			
			// load target article
			$objArticle = $this -> objArticleManager -> findFirstWhere('id', $iArticleId);
			
			// redirect to article
			$objArticleUrl = $objActionEvent -> buildActionUrl('/article/'. $objArticle -> key .'.html');
			return new UrlRedirectResponse($objArticleUrl);
		}
		
		
		public function setCommentManager(CommentManager $objCommentManager) {
			
			$this -> objCommentManager = $objCommentManager;
		}
		
		
		public function setArticleManager(ArticleManager $objArticleManager) {
			
			$this -> objArticleManager = $objArticleManager;
		}
	}